#include "indicatorbase.h"

IndicatorBase::IndicatorBase()
: m_bars(0)
, m_index(-1)
, m_capacity(2000)
{
    reset();
    recapacity(m_capacity);
}

IndicatorBase::~IndicatorBase()
{
    releaseArray();
}

void IndicatorBase::setArrayNumber(int no)
{
    double *arr = 0;
    for (int i = 0; i < no; ++i) {
        m_vecData.push_back(arr);
    }
    recapacity(m_capacity);
}

void IndicatorBase::setBars(Bars *bars)
{
    m_arraySize = bars->getSize();
    m_bars = bars;
}

double IndicatorBase::getValue(const int arrNo, const int idx)
{
    int index = idx;
    assert(index >= 0 && index < m_arraySize);
    if ((index < m_endIndex || index > m_startIndex) && index >= 0 && index < m_arraySize) {
        loadArray(index);
    }
    if (idx == m_index - 1) {
        ;
    }
    return m_vecData[arrNo][m_capacity - 1 - (index-m_endIndex)];
}

double& IndicatorBase::getElem(const int arrNo, const int idx)
{
    int index = m_index + idx;
    return m_vecData[arrNo][m_capacity - 1 - (index-m_endIndex)];
}

void IndicatorBase::releaseArray()
{
    for (int i = 0; i < m_vecData.size(); ++i) {
        if (m_vecData[i])
            delete []m_vecData[i];
    }
}

void IndicatorBase::reset()
{
    m_startIndex = -1;
    m_endIndex = -1;
}

void IndicatorBase::recapacity(int capacity)
{
    releaseArray();
    for (int i = 0; i < m_vecData.size(); ++i) {
        m_vecData[i] = new double[capacity];
    }
    m_capacity = capacity;
    reset();
}

void IndicatorBase::loadArray(int index)
{
    index += m_capacity / 2;
    if (index < 0) {
        index = 0;
    }
    else if (index > m_arraySize - 1)
        index = m_arraySize - 1;
    m_startIndex = index;
    m_endIndex = m_startIndex - m_capacity + 1;
    for (int i = m_startIndex; i >= m_endIndex && i >= 0; --i) {
        setIndex(i);
        updateValue();
    }
}